#include "movewidget.h"
#include <QMouseEvent>
#include <QDebug>


MoveWidget::MoveWidget(QObject *parent) : QObject(parent)
{
    lastPoint = QPoint(0, 0);
    pressed = false;
    leftBtn = true;
    inControl = true;
    widget = 0;
}

void MoveWidget::setControl(bool inControl)
{
    this->inControl = inControl;
}

void MoveWidget::setLeftButton(bool leftButton)
{
    this->leftBtn = leftButton;
}

void MoveWidget::setWidget(QWidget *widget)
{
    if(widget != nullptr)
    {
        this->widget = widget;
        this->widget->installEventFilter(this);
    }
}

bool MoveWidget::eventFilter(QObject *watched, QEvent *e)
{
    if(widget != nullptr && watched == widget)
    {
        QMouseEvent *mouseEvent = static_cast<QMouseEvent *>(e);
        if(mouseEvent != nullptr)
        {
            if(mouseEvent->type() == QEvent::MouseButtonPress)
            {
                if(leftBtn && mouseEvent->button() != Qt::LeftButton)
                    return false;

                if(widget->rect().contains(mouseEvent->pos()))
                {
                    lastPoint = mouseEvent->pos();
                    pressed = true;
                }
            }
            else if(mouseEvent->type() == QEvent::MouseMove && pressed)
            {
                int offsetX = mouseEvent->pos().x() - lastPoint.x();
                int offsetY = mouseEvent->pos().y() - lastPoint.y();

                int x = widget->x() + offsetX;
                int y = widget->y() + offsetY;

                if(inControl)
                {
#if 0
                    int offset = 20;

                    bool xyOut = x+widget->width()<offset || y+widget->height()<offset;
                    bool whOut = false;
                    QWidget *w = (QWidget *)widget->parent();
                    if(w != nullptr)
                    {
                        whOut = (w->width()-x<offset) || (w->height()-y<offset);
                    }
#else
                    bool xyOut = false;
                    bool whOut = false;

                    int offset = 0;
                    xyOut = x<offset || y<offset;
                    QWidget *w = (QWidget *)widget->parent();
                    if(w != nullptr)
                    {
                        whOut = x>w->width()-widget->width() || y>w->height()-widget->height();
                    }

#endif
                    if(xyOut || whOut)
                        return false;
                }
                widget->move(x, y);
            }
            else if(mouseEvent->type()==QEvent::MouseButtonRelease && pressed)
                pressed = false;
        }
    }
    return QObject::eventFilter(watched, e);
}

